import { i18n, nmAppErrorLog } from '@app-nextmesh/common/utils';
import { showLoading } from '@app-nextmesh/components';
import {
  FormField,
  FormNativeSelect,
} from '@app-nextmesh/components/Forms/components';
import { documentV2 } from '@app-nextmesh/domain';
import { useProjectStore } from '@app-nextmesh/store/project';
import { cloneDeep } from 'lodash';
import { useEffect, useRef, useState } from 'react';
import BaseForm from '../BaseForm';
import { IProps } from './types';

export default function SimulationForm({
  data: initData,
  requestType,
  onClose,
  onUpdate,
  onUpdateTitle,
}: IProps) {
  const [data, setData] = useState<any>({});
  const resetTitle = useRef({ reset: true, oldTitle: '' });
  const projectInfo = useProjectStore((state) => state.projectInfo);

  useEffect(() => {
    const newData = cloneDeep(initData.formData);
    setData(newData);
    resetTitle.current = { reset: true, oldTitle: newData.name };
    return () => {
      if (resetTitle.current.reset) {
        // 重置标题
        onUpdateTitle?.(resetTitle.current.oldTitle);
      }
    };
  }, [initData.formData]);
  const handleOk = async () => {
    const hide = showLoading();
    try {
      if (data.uuid) {
        // 有uuid更新
        const newData = await documentV2.updateSimulation(data);
        onUpdate(newData);
      }
      resetTitle.current.reset = false;
      onClose();
    } catch (error) {
      nmAppErrorLog(error);
    } finally {
      hide();
    }
  };
  function handleUpdateTitle(title: string) {
    const newData = { ...data };
    newData.name = title;
    setData(newData);
    if (requestType === 'update') {
      onUpdateTitle?.(title);
    }
  }
  function handleClose() {
    onClose();
  }
  return (
    <>
      <BaseForm
        disabled={projectInfo.readonly}
        title={data.name}
        onClose={handleClose}
        onOk={handleOk}
        updateTitle={handleUpdateTitle}>
        <FormField label={i18n.t('simulationType')}>
          <FormNativeSelect
            value={data.simuType}
            disabled
            options={[{ label: i18n.t(data.simuType), value: data.simuType }]}
          />
        </FormField>
        <FormField label={i18n.t('simulationPlugin')}>
          <FormNativeSelect
            value={data.simuPlugin}
            disabled
            options={[{ label: data.simuPlugin, value: data.simuPlugin }]}
          />
        </FormField>
      </BaseForm>
    </>
  );
}
